package com.zx.article.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 上传多个文件
 * 
 * @author 鞠卓瀚
 *
 */
public class Uploadfile {

	/**
	 * 文件上传，返回请求中的所有信息
	 * 
	 * @param req 上传请求
	 * @return result map类型的结果 文件名-文件
	 * @throws FileUploadException
	 * @throws IOException
	 */
	public static Map<String, Object> upload(HttpServletRequest req) throws FileUploadException, IOException {

//		DiskFileItemFactory 是创建FileItem 对象的工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();

//		ServletFileUpload 负责处理上传的文件数据，并将表单中每个输入项封装成一个FileItem 对象中
		ServletFileUpload upload = new ServletFileUpload(factory);

//		解析request对象，并把表单中的每一个输入项包装成一个fileItem 对象，并返回一个保存了所有FileItem的list集合
		List<FileItem> items = upload.parseRequest(req);

		Map<String, Object> result = new HashMap<>();

		List<String> names = new ArrayList<>();
		boolean isWord = false;
		for (FileItem item : items) {
//			是否是非文件域参数
			if (item.isFormField()) {
				String name = item.getFieldName();
				String value = item.getString();
				value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
				result.put(name, value);
			} else {
//				文件域参数--保存文件
				// 文件名
				String fn = getFName(item);
				FileOutputStream fos = new FileOutputStream(getFPath() + "/" + fn);
				isWord = fn.endsWith(".txt") || fn.endsWith(".doc") || fn.endsWith(".wps") || fn.endsWith(".html")
						|| fn.endsWith(".pdf") || fn.endsWith(".docx");
				if (isWord) {
					fos = new FileOutputStream("G:/w" + "/" + fn);
				}
				InputStream is = item.getInputStream();
				int length = -1;
				byte[] b = new byte[1024 * 1024];
				while (-1 != (length = is.read(b)))
					fos.write(b, 0, length);
				fos.flush();
				fos.close();
				is.close();
				names.add(fn);
			}
		}
		if (isWord) {
			result.put("file", names);
		} else {
			result.put("image", names);
		}
		return result;
	}

	/**
	 * 获得唯一的文件名，加上上传文件的扩展名
	 * 
	 * @param item
	 * @return
	 */
	private static String getFName(FileItem item) {
		String fn = item.getName();
		String uuid = UUID.randomUUID().toString();
		fn = uuid + fn.substring(fn.indexOf("."));
		return fn;
	}

	/**
	 * 保存上传来的文件的目录
	 * 
	 * @return
	 */
	private static File getFPath() {
		ResourceBundle resourceBundle = ResourceBundle.getBundle("com.zx.article.util.db");
		String imageUrl = resourceBundle.getString("imageUrl");
		File f = new File(imageUrl);
		if (!f.exists())
			f.mkdir();
		return f;
	}

	/**
	 * 拼接目录和文件名
	 * 
	 * @param filename
	 */
	public static void delFile(String filename) {
		File f = new File(getFPath() + "/" + filename);
		f.delete();
	}

}
